from fastapi import FastAPI, Depends, HTTPException
from sqlmodel import Session, select, func
from typing import List, Optional
from fastapi.middleware.cors import CORSMiddleware

from models import User, UserCreate, UserRead
from database import engine, init_db

# 创建FastAPI应用
app = FastAPI(title="用户管理API")

# 跨域配置
origins = [
    "http://localhost",
    "http://localhost:8080",  # Vue开发服务器地址
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# 数据库会话依赖
def get_session():
    with Session(engine) as session:
        yield session


# 初始化数据库
@app.on_event("startup")
def on_startup():
    init_db()


# 创建用户
@app.post("/api/users/", response_model=UserRead)
def create_user(user: UserCreate, session: Session = Depends(get_session)):
    # 检查邮箱是否已存在
    db_user = session.exec(select(User).where(User.email == user.email)).first()
    if db_user:
        raise HTTPException(status_code=400, detail="Email already registered")

    db_user = User.from_orm(user)
    session.add(db_user)
    session.commit()
    session.refresh(db_user)
    return db_user


# 获取用户列表
@app.get("/api/users/")
def read_users(
        page: int = 0,
        pageSize: int = 10,
        keyword: Optional[str] = None,
        session: Session = Depends(get_session)
    ):
    print('page==', page)
    print('limit==', pageSize)
    print('keyword==', keyword)
    query = select(User)
    # 搜索功能
    if keyword:
        query = query.where(User.username.contains(keyword))
    users = session.exec(query.offset(page*10).limit(pageSize)).all()
    total = session.query(User).count()
    return {
        "items": users,
        "total": total
    }


# 获取单个用户
@app.get("/api/users/{user_id}", response_model=UserRead)
def read_user(user_id: int, session: Session = Depends(get_session)):
    user = session.get(User, user_id)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user


# 更新用户
@app.patch("/api/users/{user_id}", response_model=UserRead)
def update_user(user_id: int, user: UserCreate, session: Session = Depends(get_session)):
    db_user = session.get(User, user_id)
    if not db_user:
        raise HTTPException(status_code=404, detail="User not found")

    user_data = user.dict(exclude_unset=True)
    for key, value in user_data.items():
        setattr(db_user, key, value)

    session.add(db_user)
    session.commit()
    session.refresh(db_user)
    return db_user


# 删除用户
@app.delete("/api/users/{user_id}")
def delete_user(user_id: int, session: Session = Depends(get_session)):
    user = session.get(User, user_id)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")

    session.delete(user)
    session.commit()
    return {"ok": True}